﻿using System;
using System.Collections.Generic;
using System.Linq;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.TinyIoc;
using Nancy.Authentication.Stateless;
using Nancy.Cryptography;
using Nancy.Authentication.Forms;

namespace NancyOauth2
{
    public class BootStrapper:DefaultNancyBootstrapper
    {
        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);

            // Here we register our user mapper as a per-request singleton.
            // As this is now per-request we could inject a request scoped
            // database "context" or other request scoped services.
            container.Register<IUserMapper, UserDatabase>();
        }

        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            var statelessAuthConfiguration = new StatelessAuthenticationConfiguration(nancyContext =>
            {
                string authorization = nancyContext.Request.Headers["Authorization"].FirstOrDefault();

                string token = "";
                if (authorization?.ToLower().Contains("Bearer".ToLower()) == true)
                {
                    token = authorization.Replace("Bearer".ToLower(), "").Trim();
                }

                return UserDatabase.GetUserFromToken(token);
            });

            StatelessAuthentication.Enable(pipelines, statelessAuthConfiguration);

            //Jsonp.Disable(pipelines);//默认开启的Jsonp
        }

        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(requestContainer, pipelines, context);
            
            var maxAge = 21600;
            //CORS Enable
            pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
            {
                if (ctx.Request.Headers.Keys.Contains("Origin"))
                {
                    var origins = "" + string.Join(" ", ctx.Request.Headers["Origin"]);
                    ctx.Response.Headers["Access-Control-Allow-Origin"] = origins;
                    ctx.Response.WithHeader("Access-Control-Allow-Credentials", "true")
                        .WithHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS")
                        .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type,authorization")
                        .WithHeader("Access-Control-Max-Age", maxAge.ToString());
                }
            });
        }
    }
}